package com.example.filedownload;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

public class Util {
    public static String getDefaultDownloadPath(){
        String username = System.getProperty("user.name");
        return "C:\\Users\\"+username+"\\Downloads\\";
    }


    public static String getFileName(String url){
        return url.substring(url.lastIndexOf('/')+1);
    }

    public static long getFileLength(String downloadUrl) throws IOException {
        if(downloadUrl == null || "".equals(downloadUrl)){
            return 0L ;
        }
        URL url = new URL(downloadUrl);
        HttpURLConnection conn = null;
        try {
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("HEAD");
            conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows 7; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.73 Safari/537.36 YNoteCef/5.8.0.1 (Windows)");
            return (long) conn.getContentLength();
        } catch (IOException e) {
            return 0L;
        } finally {
            conn.disconnect();
        }
    }

    public static void openExplorer(){
        try {
            System.out.println(getDefaultDownloadPath());
            Runtime.getRuntime().exec("explorer "+getDefaultDownloadPath());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
